<?

$_table = 'sec_role';


if (($a = (int)param('edit')) && ($DATA['object'] = datafetch('db_item', tb($_table), "id=$a"))) {


$DATA['objects'] = datafetch_array('db_list', array('table' => tb('sec_obj'), 'order' => 'kind, name', 'index' => 'id'));


	switch (action(array('editor_save'))) {
	
		case 'editor_save':
		
			if ($t = postdata('name')) {	// some data received
			
				$attr = postdata('ro_def') ? RO_DEFAULT : 0;
			
//dbdebug();
				dataset('db_update', tb($_table), array(
					'name' => $t,
					'attr' => $attr
				), "id=$a");


				dataset('db_delete', tb('sec_perm'), "id_role=$a");
				
				if (is_array($d = postdata('right'))) { $temp = array();

					$rp = postdata('rp', array());
					
//debug($d, 'd');				
//debug($rp, 'rp');				
					foreach($d as $v) {
						
						switch($DATA['objects'][$v]['kind']) {
							
							case 0: // page
								if (in_array($v, $rp))
									$temp[] = array('id_obj' => $v, 'id_role' => $a);
								else {
									$rx = postdata("r$v", array());
									foreach($rx as $r)
										$temp[] = array('id_obj' => $v, 'id_role' => $a, 'id_parent' => $r);
								}
								break;

							case 1: // object
								$temp[] = array('id_obj' => $v, 'id_role' => $a);
								break;
						}
						
						
					}
					
					dataset('db_insert', tb('sec_perm'), $temp);
				}
				

			} else {	// empty data
			}
			
			header("Location: "._transformURL($CURRENT->url, array('remove_param' => 'edit')));
			exit;

			break;

	}

$DATA['pages'] = datafetch_array('structmap', array('bit' => 0, 'path' => '/'));

$DATA['perms'] = array();
$temp = datafetch_array('db_list', array('table' => tb('sec_perm'), 'where' => "id_role=$a"));

//debug($temp);

foreach($temp as $v)
	if ($v['id_parent']) {
		if (isset($DATA['perms'][$v['id_obj']]))
			$DATA['perms'][$v['id_obj']]['id_parent'][] = $v['id_parent'];
		else {
			$v['id_parent'] = array($v['id_parent']);
			$DATA['perms'][$v['id_obj']] = $v;
		}
	} else
		$DATA['perms'][$v['id_obj']] = $v;

//debug($DATA['objects']);
//debug($DATA['perms']);
//exit;

	// !!! fix crumbs
	$DATA['crumb'][] = array('name' => $DATA['object']['name']);
	$DATA['crumb'] = array_mark_bounds($DATA['crumb']);




} else {								// **** bad article ****

	header("Location: "._transformURL($CURRENT->url, array('remove_param' => 'edit')));
	exit;
}
